<template>
  <el-tree-select
    v-model="value"
    :data="_data"
    v-bind="config"
    :filter-node-method="filterNodeMethod"
    @change="(val:any) => changeValue(val)"
  >
  </el-tree-select>
</template>

<script setup lang="ts">
import { SearchFormItem } from '@/types'
import { useI18n } from 'vue-i18n'
import request from '@/utils/http'
import { computed, reactive, ref, watch } from 'vue'

const { t } = useI18n()

// 定义组件值类型
export type ValueVO = unknown

// 定义组件props
const prop = defineProps<{
  value: ValueVO // 选择框的值
  item: SearchFormItem // 表单项配置
}>();

// 定义emit事件
const emit = defineEmits<{
  (e: 'update:value', value: ValueVO): void
}>()

// 计算属性:处理v-model双向绑定
const value = computed({
  get: () => prop.value as string,
  set: (value: ValueVO) => emit('update:value', value)
})

// 合并默认配置和自定义配置
const config = reactive({
  placeholder: `${t('table.searchBar.searchSelectPlaceholder')}${prop.item.label}`,
  ...(prop.item.config || {})
})

// 选择框值变化处理函数
const changeValue = (val: unknown): void => {
  if (prop.item.onChange) {
    prop.item.onChange({
      prop: prop.item.prop,
      val
    })
  }
}

const _data = ref<any[]>([])
const remote = ref<any>()

const getTreeOptions = (url: string, method: string, params: any) => {
  if (method.toLowerCase() === 'post') {
    return request.post<any>({
      url: url,
      data: params // POST 请求通常使用 data
    })
  } else {
    return request.get<any>({
      url: url,
      params // GET 请求使用 params
    })
  }
}

const filterNodeMethod = (value: any, data: any) => {
  if (!value) return true
  return data.label.includes(value)
}

const getRemoteData = async () => {
  try {
    const response = await getTreeOptions(
      remote.value?.url,
      remote.value?.method || 'get',
      remote.value?.params || {}
    )
    _data.value = response || [] // 根据实际响应结构调整
  } catch (error) {
    console.error('Failed to fetch tree data:', error)
    _data.value = []
  }
}

const getLocalData = () => {
  if (prop.item.options) {
    if (Array.isArray(prop.item.options)) {
      _data.value = prop.item.options
    } else {
      _data.value = prop.item.options()
    }
  } else {
    _data.value = []
  }
}



// 优化数据加载逻辑
watch(() => prop.item, async (newItem) => {
  if (newItem.remote?.enabled && newItem.remote?.url) {
    remote.value = newItem.remote
    getRemoteData()
  } else {
    getLocalData()
  }
}, { immediate: true, deep: true })
</script>